{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#|default_exp models.FCNPlus"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# FCNPlus"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ">This is an unofficial PyTorch implementation created by Ignacio Oguiza - oguiza@timeseriesAI.co"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#|export\n",
    "from tsai.imports import *\n",
    "from fastai.layers import *\n",
    "from tsai.models.layers import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#|export\n",
    "class FCNPlus(nn.Sequential):\n",
    "    def __init__(self, c_in, c_out, layers=[128, 256, 128], kss=[7, 5, 3], coord=False, separable=False, use_bn=False, fc_dropout=0.,\n",
    "                 zero_norm=False, act=nn.ReLU, act_kwargs={}, residual=False, custom_head=None):\n",
    "        assert len(layers) == len(kss)\n",
    "        backbone = _FCNBlockPlus(c_in, layers=layers, kss=kss, coord=coord, separable=separable,\n",
    "                                 zero_norm=zero_norm, act=act, act_kwargs=act_kwargs, residual=residual)\n",
    "        self.head_nf = layers[2]\n",
    "        head_layers = [nn.AdaptiveAvgPool1d(1), Squeeze(-1)]\n",
    "        if use_bn: head_layers += [nn.BatchNorm1d(layers[-1])]\n",
    "        if fc_dropout != 0: head_layers += [nn.Dropout(fc_dropout)]\n",
    "        head_layers += [nn.Linear(layers[-1], c_out)]\n",
    "        if custom_head: head = custom_head(self.head_nf, c_out) # custom head passed as a partial func with all its kwargs\n",
    "        else: head = nn.Sequential(*head_layers)\n",
    "        super().__init__(OrderedDict([('backbone', backbone), ('head', head)]))\n",
    "\n",
    "\n",
    "class _FCNBlockPlus(Module):\n",
    "    def __init__(self, c_in, layers=[128, 256, 128], kss=[7, 5, 3], coord=False, separable=False,\n",
    "                 zero_norm=False, act=nn.ReLU, act_kwargs={}, residual=False):\n",
    "        self.residual = residual\n",
    "        self.convblock1 = ConvBlock(\n",
    "            c_in, layers[0], kss[0], coord=coord, separable=separable, act=act, act_kwargs=act_kwargs)\n",
    "        self.convblock2 = ConvBlock(\n",
    "            layers[0], layers[1], kss[1], coord=coord, separable=separable, act=act, act_kwargs=act_kwargs)\n",
    "        self.convblock3 = ConvBlock(layers[1], layers[2], kss[2], coord=coord, separable=separable, zero_norm=zero_norm if residual else False,\n",
    "                                    act=None if residual else act, act_kwargs=act_kwargs)\n",
    "        if residual:\n",
    "            self.shortcut = BN1d(layers[2]) if c_in == layers[2] else ConvBlock(\n",
    "                c_in, layers[2], 1, coord=coord, act=None)\n",
    "        self.add = Add() if residual else Noop\n",
    "\n",
    "    def forward(self, x):\n",
    "        if self.residual:\n",
    "            res = x\n",
    "        x = self.convblock1(x)\n",
    "        x = self.convblock2(x)\n",
    "        x = self.convblock3(x)\n",
    "        if self.residual:\n",
    "            x = self.add(x, self.shortcut(res))\n",
    "        return x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "xb = torch.rand(16, 3, 10)\n",
    "test_eq(FCNPlus(3, 2)(xb).shape, [xb.shape[0], 2])\n",
    "test_eq(FCNPlus(3, 2, coord=True, separable=True, act=Swish, residual=True)(xb).shape, [xb.shape[0], 2])\n",
    "test_eq(nn.Sequential(*FCNPlus(3, 2).children())(xb).shape, [xb.shape[0], 2])\n",
    "test_eq(FCNPlus(3, 2, custom_head=partial(mlp_head, seq_len=10))(xb).shape, [xb.shape[0], 2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tsai.models.utils import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Sequential(\n",
       "  (0): AdaptiveAvgPool1d(output_size=1)\n",
       "  (1): Squeeze(dim=-1)\n",
       "  (2): Linear(in_features=128, out_features=3, bias=True)\n",
       ")"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model = build_ts_model(FCNPlus, 2, 3)\n",
    "model[-1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tsai.models.FCN import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_eq(count_parameters(FCN(3,2)), count_parameters(FCNPlus(3,2)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "FCNPlus(\n",
       "  (backbone): _FCNBlockPlus(\n",
       "    (convblock1): ConvBlock(\n",
       "      (0): Conv1d(3, 128, kernel_size=(7,), stride=(1,), padding=(3,), bias=False)\n",
       "      (1): BatchNorm1d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (2): ReLU()\n",
       "    )\n",
       "    (convblock2): ConvBlock(\n",
       "      (0): Conv1d(128, 256, kernel_size=(5,), stride=(1,), padding=(2,), bias=False)\n",
       "      (1): BatchNorm1d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (2): ReLU()\n",
       "    )\n",
       "    (convblock3): ConvBlock(\n",
       "      (0): Conv1d(256, 128, kernel_size=(3,), stride=(1,), padding=(1,), bias=False)\n",
       "      (1): BatchNorm1d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n",
       "      (2): ReLU()\n",
       "    )\n",
       "    (add): Sequential()\n",
       "  )\n",
       "  (head): Sequential(\n",
       "    (0): AdaptiveAvgPool1d(output_size=1)\n",
       "    (1): Squeeze(dim=-1)\n",
       "    (2): Linear(in_features=128, out_features=2, bias=True)\n",
       "  )\n",
       ")"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "FCNPlus(3,2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/javascript": "IPython.notebook.save_checkpoint();",
      "text/plain": [
       "<IPython.core.display.Javascript object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/Users/nacho/notebooks/tsai/nbs/103c_models.FCNPlus.ipynb saved at 2022-11-21 13:16:09\n",
      "Correct notebook to script conversion! 😃\n",
      "Monday 21/11/22 13:16:11 CET\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "                <audio  controls=\"controls\" autoplay=\"autoplay\">\n",
       "                    <source src=\"data:audio/wav;base64,UklGRvQHAABXQVZFZm10IBAAAAABAAEAECcAACBOAAACABAAZGF0YdAHAAAAAPF/iPh/gOoOon6w6ayCoR2ZeyfbjobxK+F2Hs0XjKc5i3DGvzaTlEaraE+zz5uLUl9f46fHpWJdxVSrnfmw8mYEScqUP70cb0Q8X41uysJ1si6Eh1jYzXp9IE2DzOYsftYRyoCY9dJ/8QICgIcEun8D9PmAaBPlfT7lq4MFIlh61tYPiCswIHX+yBaOqT1QbuW7qpVQSv9lu6+xnvRVSlyopAypbGBTUdSalrSTaUBFYpInwUpxOzhti5TOdndyKhCGrdwAfBUcXIJB69p+Vw1egB76+n9q/h6ADglbf4LvnIHfF/981ODThF4m8HiS0riJVjQ6c+/EOZCYQfJrGrhBmPVNMmNArLKhQlkXWYqhbaxXY8ZNHphLuBJsZUEckCTFVHMgNKGJytIDeSUmw4QN4Qx9pReTgb3vYX/TCBuApf75f+P5Y4CRDdN+B+tngk8c8nt03CKGqipgd13OhotwOC5x9MCAknFFcmlmtPmagFFFYOCo0qRzXMhVi57pryNmIEqJlRi8bm52PfuNM8k4dfQv+4cO12l6zCGdg3jl730uE/KAPvS+f0wEAoAsA89/XfXQgBESIn6S5luDtiC8eh/YmIfpLqt1OMp5jXg8/24MveqUNUnPZsqw0Z3yVDldnaUOqIZ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4CECU9/De+vgVQY5nxh4POEzybJeCTS5YnCNAZzhsRzkP1Bsmu4t4aYU07nYuerA6KWWcJYO6HHrKJjaE3Zl624UWz/QOOPjcWHc7QzdIk40yl5tCWjhIDhJX0xF4CBMvBsf10IF4Ac//Z/bPlsgAcOwn6S6n6CwxzUewLcRoYaKzV38M23i9o493CNwL6S1UUuaQe0QpvbUfdfiqglpcRccFU+nkWwambASUiVfLyqbg49xY2eyWh1hy/Sh37XjHpaIYKD7OUEfrgS5IC09MV/1gMBgKMDyH/n9N6AhhINfh7mdoMoIZt6r9fAh1cvfHXNya6N4DzDbqi8K5WWSYlmbbAdnkpV6FxJpWSo1V8DUmGb3rMRaQBG2JJgwN9wCDnNi8HNI3dKK1aG0dvHe/UciIJf6rt+Og5wgDn59X9P/xWAKQhxf2XweYH+FjB9suGVhIMlOnlo02GJhTOdc7vFyo/TQGxs2Li7lz9NwmPurBihnVi7WSWiwKvGYntOpJiOt5drKUKMkFnE8HLxNPmJ9NG4eP8mAYUv4Np8hhi3gdruSX+3CSWAwP38f8f6UoCuDPF+6Os8gnAbKnxQ3d2F0imydzDPKIuiN5lxu8EKkrFE82kftW2az1DbYImpMqTUW3FWIJ83r5hl2koJlla7+m0+PmSOZcjcdMgwS4g11iZ6qCLUg5jkxn0QFA6BWvOvfzEFBIBHAtp/Qfa3gC4RSH5y5yeD2B/8evnYS4cULgR2CMsUja47cG/QvW6UeEhXZ3+xP51GVNVdP6Zpp+1eDFM5nMeySWghR4+TNL85cD46YIyCzKJ2kCzEhoTabXtGHs+CCemJfpMPjoDe9+t/qQALgM8Gj3++8UaBqRV2fQTjO4Q3JKd5r9TgiEYyMHTxxiWPpz8jbfq585YpTJpk960xoKFXsVoTo7yq6GGMTw==\" type=\"audio/wav\" />\n",
       "                    Your browser does not support the audio element.\n",
       "                </audio>\n",
       "              "
      ],
      "text/plain": [
       "<IPython.lib.display.Audio object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "#|eval: false\n",
    "#|hide\n",
    "from tsai.export import get_nb_name; nb_name = get_nb_name(locals())\n",
    "from tsai.imports import create_scripts; create_scripts(nb_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "python3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
